package com.hiss.basic.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.hiss.basic.client.system.ISysLoginLogService;
import com.hiss.basic.client.system.ISysOperateLogService;
import com.hiss.basic.model.system.domain.SysLoginLogDomain;
import com.hiss.basic.model.system.domain.SysOperateLogDomain;
import com.hiss.basic.starter.log.event.LoginLogEvent;
import com.hiss.basic.starter.log.event.OperateLogEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@Component
public class LogActionEventListener {

    @Resource
    private ISysLoginLogService sysLoginLogService;

    @Resource
    private ISysOperateLogService sysOperateLogService;

    @Async
    @EventListener
    public void handle(LoginLogEvent event) {
        HttpServletRequest request = event.getRequest();
        String ip = ServletUtil.getClientIP(request);
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));

        SysLoginLogDomain domain = new SysLoginLogDomain();
        domain.setUsername(event.getUsername());
        domain.setOs(userAgent.getOs().getName());
        domain.setBrowser(userAgent.getBrowser().getName());
        domain.setIp(ip);
        domain.setStatus(event.getStatus());
        domain.setLoginTime(LocalDateTime.now());

        sysLoginLogService.save(domain);
    }

    @Async
    @EventListener
    public void handle(OperateLogEvent event) {
        SysOperateLogDomain domain = BeanUtil.copyProperties(event, SysOperateLogDomain.class);
        sysOperateLogService.save(domain);
    }
}
